Functions


Definition:

Function: (1) In programming, a named section of a program that performs a specific task. In this sense, a function is a type of procedure or routine. Some programming languages make a distinction between a function, which returns a value, and a procedure, which performs some operation but does not return a value. Most programming languages come with a prewritten set of functions that are kept in a library. You can also write your own functions to perform specialized tasks. (2) The term function is also used synonymously with operation and command. For example, you execute the delete function to erase a word.


Functions are an essential ingredient of all programs, large and small, and serve as our primary medium to express computational processes in a programming language. Fundamentally, the qualities of good functions all reinforce the idea that functions are abstractions.

  • Each function should have exactly one job. That job should be identifiable with a short name and characterizable in a single line of text. Functions that perform multiple jobs in sequence should be divided into multiple functions.
  • Don't repeat yourself is a central tenet of software engineering. The so-called DRY principle states that multiple fragments of code should not describe redundant logic. Instead, that logic should be implemented once, given a name, and applied multiple times. If you find yourself copying and pasting a block of code, you have probably found an opportunity for functional abstraction.
  • Functions should be defined generally. Squaring is not in the Python Library precisely because it is a special case of the pow function, which raises numbers to arbitrary powers.

Source

It may not be clear why it is worth the trouble to divide a program into functions. There are several reasons:

  • Creating a new function gives you an opportunity to name a group of statements, which makes your program easier to read and debug.
  • Functions can make a program smaller by eliminating repetitive code. Later, if you make a change, you only have to make it in one place.
  • Dividing a long program into functions allows you to debug the parts one at a time and then assemble them into a working whole.
  • Well-designed functions are often useful for many programs. Once you write and debug one, you can reuse it.

These guidelines improve the readability of code, reduce the number of errors, and often minimize the total amount of code written. Decomposing a complex task into concise functions is a skill that takes experience to master. Fortunately, Python provides several features to support your efforts.

Source

How do we square a number? (Lets pretend we do not all have calculators, phones or computers to do this for us!)


In [2]:
6 * 6


Out[2]:
36

The square is just a number multiplied by itself. In python the code that as:


In [3]:
6**2


Out[3]:
36

We can also assign this calculation to a varaible:


In [4]:
a = 6**2

What happens if we need to square different numbers in our hypothetical program?

  • Cut and paste and change each time?

In [5]:
a = 6**2
b = 7**2

print(a)
print(b)


36
49

What if I want to square a varaible x and set it equal to a? What if we want to square the variable y and set it equal to b?

This takes the code to a single level of abstraction


In [ ]:
x = 6
y = 7

a = x**2
b = y**2

print(a)
print(b)

We see that we are executing the same code but with a different input, x or y. We have abstracted the code a little to introduce the varaibles x and y.

How do we convert this to a function?

What is the pattern we see in the code above?

  • initialize a varaible

      x = 6
  • square the varaible and set the result equal to another variable

      a = x**2
  • print the resulting varaible

      print(a)

We perform the same pattern again by replacing a with b and x with y.


In [ ]:
x = 6
a = x**2
print(a)

How do we convert this to a function, exactly as it is?

Creating a Function


In [6]:
def square_x():
    x = 6
    a = x**2
    print(a)
def = define for defining function. Give it a name: square_x. because it is a function, also needs open and close () and a colon:

What happens when we run this? . . . Nothing!

calling a function = running it. just defining it is not enough

Functions must be called to be run. Lets call the function: to call a function, simply print its name and do open and close parentheses


In [7]:
square_x()


36

This function prints the number 36 only. Can call it: 'print 36' if want; need to further abstract to see power of this because have nothing in middle of parentheses (no parameters), this function works. Lets chenge the function to give parameters.

Parameters

Parameters are variables that serve as input to a function. We can extract the x varaible from our code to create a parameter x.


In [8]:
def square(x):
    # x = 6
    a = x**2
    print(a)

The parameters are then fed into the functiona t the time of the call:


In [15]:
square(square(6))


Out[15]:
1296

No longer defining x value within function. now do this outside of function. we now have function that will square any number given to it

Returning a Value From a Function

In our example we are printing the result of our function within hte function. What if we wanted to use the result of our function? We can change the function to return a result and tehn we can save teh result and print the result.


In [19]:
x = 3 #set "global" variable equal to 3

def square(x): #still have single parameter, x; must define a function before calling it
    a = x**2
    return a #return is a keyword that allows us to return the result we computed earlier (Saves the result of function into variable sqr)

square(x)


Out[19]:
9

Now this function has a huge boost in capability by being called to a variable

What are the Requirements of a Function?

What are the requirements of a function:

  • the def keyword
  • A function name (see PEP8 guidelines for function names here)
  • need open and close parentheses
  • A semicolon ":" at the end of the def line
  • One or more lines of code in the body

Optional components:

  • Zero or more parameters
  • Zero or more return variables

      def function_name([parameters]):
          body - some code which must be indented
          [return object(s)]

Note to save functions, would create file like burkes_functions.py, this would be a text file

What if We Need Two or More Parameters?

Lets abstract our function again and enable it to raise any number to any power.


In [ ]:
def square(x, y): #function with 2 parameters
    a = x**y
    return a

sqr = power(6, 2) #must feed in both parameters when call code
print(sqr)

Does teh name square make sense any more?


In [20]:
def power(x, y): #function with 2 parameters
    a = x**y
    return a

sqr = power(6, 2) #must feed in both parameters when call code
print(sqr)


36

In [21]:
def power(x, y): #function with 2 parameters
    return x**y

sqr = power(6, 2) #must feed in both parameters when call code
print(sqr)


36

Setting a Default Value to the Parameter


In [ ]:
def power(x, y=2): #removes necessity of feeding second value in when call function
    a = x**y
    return a

sqr = power(6) #do not need to give value for y because have defaulted it, but can define value if want to automatically override default
print(sqr)

In [22]:
help(power)


Help on function power in module __main__:

power(x, y)

Describing Functions in Python

To define a function use the keyword def, as in:


In [23]:
def my_function():
    """This function prints hello""" #three double quotes around statement define a doc string
    print("hello")
    return

Note the use of the docstring, which will allow us to use help function: -it can also extend to multiple lines, so be as descriptive as you can


In [24]:
help(my_function) #help will tell entire description that is supplied in doc string (for ex. could put defaults here)


Help on function my_function in module __main__:

my_function()
    This function prints hello

Help on function my_function in module main:

my_function()
    This function prints hello

Returning More Than One Result


In [31]:
def power(x, y=2):
    a = x**y
    return a, x, y

sqr, num, power = power(y=6, x=3)
print(sqr)
print(sqr,num,power)


729
729 3 6

Pass by Reference vs Value (can SKIP over this - didn't discuss in class)

All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example:


In [ ]:
#!/usr/bin/python

# Function definition is here
def changeme( mylist ):
   "This changes a passed list into this function"
   mylist.append([1,2,3,4]);
   print("Values inside the function: ", mylist)
   return

# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print("Values outside the function: ", mylist)

Calling Functions within Functions


In [ ]:
def power(x, y=2):
    a = x**y
    return a

sqr = power(power(2)) #i've raised 2 to the second power to get 4 and feeding 4 into power again to get squared
print(sqr)

Functions Checklist:

Source

These may help you as you begin to work with functions:

  • Did you start your function definition with def?
  • Does your function name have only characters and _ (underscore) characters?
  • Did you put an open parenthesis ( right after the function name?
  • Did you put your arguments after the parenthesis ( separated by commas?
  • Did you make each argument unique (meaning no duplicated names)?
  • Did you put a close parenthesis and a colon ): after the arguments?
  • Did you indent all lines of code you want in the function four spaces? No more, no less.
  • Did you "end" your function by going back to writing with no indent (dedenting we call it)?

When you run ("use" or "call") a function, check these things:

  • Did you call/use/run this function by typing its name?
  • Did you put the ( character after the name to run it?
  • Did you put the values you want into the parenthesis separated by commas?
  • Did you end the function call with a ) character?

In [ ]: